package comment

import (
	"encoding/json"
	"fmt"
	"net/url"
	"renrenwaigua/oauth"
	"strconv"
)

func Put(t *oauth.Transport, cp CommentPut) (*putResponse, error) {

	vals := url.Values{}
	vals.Set("access_token", t.Token.AccessToken)
	vals.Set("content", cp.Content)
	vals.Set("commentType", cp.CommentType)
	vals.Set("entryOwnerId", strconv.FormatInt(cp.EntryOwnerId, 10))
	vals.Set("entryId", strconv.FormatInt(cp.EntryId, 10))
	if cp.TargetUserId != 0 {
		vals.Set("targetUserId", strconv.FormatInt(cp.TargetUserId, 10))
	}

	r, err := t.Client().PostForm(apiComment+apiCommentPut, vals)
	if err != nil {
		return nil, err
	}
	if r.StatusCode != 200 {
		fmt.Println("comment:put:status code:", r.StatusCode)
		buf := make([]byte, 1024)
		n, err := r.Body.Read(buf)
		if err != nil {
			fmt.Println("comment:put:body read:", err.Error())
		} else {
			fmt.Println("comment:put:body:", string(buf[:n]))
		}
	}

	cr := putResponse{}
	err = json.NewDecoder(r.Body).Decode(&cr)
	if err != nil {
		fmt.Println(err.Error())
	}

	return &cr, nil
}
